import React, { useEffect, useState } from 'react';
import {
  Table, Checkbox, Row, Modal, Form, Input, Col, message, InputNumber, Select, Button, Radio, DatePicker,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import Cropper from 'react-cropper'
import 'cropperjs/dist/cropper.css'
import {
  getAlbum,
} from '@/services/goodCenter/goods';
import { connect } from 'dva';
import Asort from '@/components/sorttable/index'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 20 },
  },
}
const { Option } = Select
const { TextArea } = Input
const { MonthPicker } = DatePicker

const statusLists = ['', '空闲/正常', '已预定', '使用中', '维修中']
const arrtion = ['否', '是']
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    key: 'index',
  },
  {
    title: '台房名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '楼层',
    align: 'center',
    key: 'floorName',
  },
  {
    title: '类型',
    align: 'center',
    key: 'typeName',
  },
  {
    title: '保底消费',
    align: 'center',
    key: 'limitAmount',
  },
  {
    title: '状态',
    align: 'center',
    key: 'status',
    render: p => (<span>{ statusLists[p.status] }</span>),
  },
  {
    title: '是否开启预定',
    align: 'center',
    key: 'isReservation',
    render: p => (<span>{ arrtion[p.isReservation] }</span>),
  },
  {
    title: '是否开启排班',
    align: 'center',
    key: 'isScheduling',
    render: p => (<span>{ arrtion[p.isScheduling] }</span>),
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'createTime',
  },
  {
    title: '二维码',
    align: 'center',
    key: 'accountQrcode',
    render: p => (<Button type="ghost" onClick={() => window.open(p.accountQrcode)}>下载二维码</Button>),
  },
];
const statusList = [
  {
    label: '空闲/正常',
    value: '1',
  },
  {
    label: '已预定',
    value: '2',
  },
  {
    label: '使用中',
    value: '3',
  },
  {
    label: '维修中',
    value: '4',
  },
]
const addGood = props => {
  const { getFieldDecorator } = props.form;
  const { global } = props
  const { menus } = global
  const getCurrentBtn = menu => {
    const path = props.location.pathname
    return menu.map(i => i.path == path ? i.button : getCurrentBtn(i.children || []))
      .filter(i => i && i.length != 0)
      .reduce((acc, val) => acc.concat(val), []) || [];
  }
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [types, settypes] = useState([]);
  const [types2, settypes2] = useState([]);
  const [month, setmonth] = useState(null);
  const [roomtypes, setroomtypes] = useState([]);
  const [staffList, setStaffList] = useState([]);
  const [mondata, setmondata] = useState([]);
  const [endTime, setendTime] = useState(null);
  const [startTime, setstartTime] = useState(null);
  const [checkhour, setcheckhour] = useState([]);
  const [checkmin, setcheckmin] = useState([]);
  const [templateList, settemplateList] = useState([]);
  const [brandList, setbrandList] = useState([]);
  const [picList, setpicList] = useState([]);
  const [imgs, setimgs] = useState([]);
  const [curPic, setcurPic] = useState('');
  const [roomname, setroomname] = useState('');
  const [mycropper, setmycropper] = useState('');
  const [curUrl, setcurUrl] = useState('');
  // const [buts, setbuts] = useState([]);
  const [hasTypeAdd, sethasTypeAdd] = useState(false);
  const [showMyImage, setshowMyImage] = useState(false);
  const [hasGoodAdd, sethasGoodAdd] = useState(false);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const CheckBtn = buts => {
    if (buts.length > 0) {
      buts.forEach(v => {
        if (v.type === 1) {
          sethasTypeAdd(true)
        } else if (v.type === 3) {
          sethasGoodAdd(true)
        }
      })
    }
  }
  const [info, setInfo] = useState({
    resGoodsExtend: {},
    resGoods: {},
    resGoodsImages: ['God', 'God21', 'God4124', '142412', '123', '设定分', '请问'],
  });
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  const [confirmLoading, setconfirmLoading] = useState(false);

  // 列表
  const getList = async params => {
    // const r = await handleSupplier(params, 'GET');
    // if (r.data && r.data.data) {
    //   setColData(r.data.data);
    // }
  };
  useEffect(() => {
    getAlbum().then(res => {
      if (res.data && res.code === '0') {
        if (res.data.length > 0) {
          setpicList(res.data)
          if (res.data[0].resCommonsAlbums && res.data[0].resCommonsAlbums.length > 0) {
            setcurPic(res.data[0].resCommonsAlbums[0].id)
          } else {
            setcurPic(res.data[0].id)
          }
        }
      }
    })
    getList(listQuery)
  }, [])
  useEffect(() => {
    CheckBtn(getCurrentBtn(menus))
  }, [menus]);
  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  // 新增/修改 模态框
  const handleStatus = () => {
    setState(true)
  };
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };
  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // let med = 'POST'
        // if (values.id) {
        //   med = 'PUT'
        // }
        // setconfirmLoading(true)
        // handleSupplier({ storeBusiness: values }, med).then(() => {
        //   getList(listQuery)
        //   setState(!isShow);
        //   setconfirmLoading(false)
        // }).catch(() => {
        //   setconfirmLoading(false)
        // })
      }
    });
  };
  const renderImgs = () => {
    imgs.map((val, i) => (
      <Col xs={12} sm={8} md={6} lg={4} xl={3} key={i}>
        <div className="aimg">
          <div className="imgBox">
            <img src={val.url} alt=""/>
          </div>
          <div className="imgtext">{val.name}</div>
          <div className="imgBtn">
            <Button type="primary" size="small">选择</Button>
            <Button type="danger" size="small">删除</Button>
          </div>
        </div>
      </Col>
    ))
  }
  return (
    <PageHeaderWrapper>
      <div style={{backgroundColor: '#fff', padding: '20px', marginBottom: 10}}>
        <Radio checked>使用自定义类目</Radio>
        <p className="addgoodtip">适用于商家的非常规商品，商品规格属性可以自由设置。商品信息如需要同步到其它平台店铺，请使用综合类目。</p>
        <Select placeholder="请选择一级分类" style={{width: 250}}>
          { types.map(v => (
            <Option key={v.id}>{v.name}</Option>
          )) }
        </Select>
        <Select placeholder="请选择二级分类" style={{width: 250, marginLeft: 15}}>
          { types2.map(v => (
            <Option key={v.id}>{v.name}</Option>
          )) }
        </Select>
        { hasTypeAdd ? (<Button style={{marginLeft: 15}} type="primary" onClick={handleStatus}>新增分类</Button>) : null }
      </div>
      <div className="bbox bgfff">
        <p className="ctitle">基本信息</p>
        <Form {...formItemLayout}>
          <Form.Item label="品牌">
            {getFieldDecorator('resGoods.brandId', {
              initialValue: info.resGoods.brandId,
            })(<Select placeholder="请选择品牌">
              {brandList.map(r => <Option key={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
          <Form.Item label="商品名称">
            {getFieldDecorator('resGoods.goodsName', {
              initialValue: info.resGoods.goodsName,
              rules: [
                {
                  required: true,
                  message: '请输入商品名称',
                },
              ],
            })(<Input placeholder="请输入商品名称" />)}
          </Form.Item>
          <Form.Item label="商品简介">
            {getFieldDecorator('resGoods.goodsDesc', {
              initialValue: info.resGoods.goodsDesc,
              rules: [
                {
                  required: true,
                  message: '请输入商品简介',
                },
              ],
            })(<TextArea placeholder="请输入商品简介" />)}
            <div className="addgoodtip">微信分享给好友时会显示这里的文案，如果没有填写，则显示商品名称</div>
          </Form.Item>
          <Form.Item label="商品图片">
            <Asort items={info.resGoodsImages} upload={() => { setshowMyImage(true) }} />
          </Form.Item>
          <Form.Item label="商品属性">
            {getFieldDecorator('contractNumber', {
              initialValue: info.contractNumber,
              rules: [
                {
                  required: true,
                  message: '商品属性',
                },
              ],
            })(<Input placeholder="商品属性" />)}
          </Form.Item>
          <Form.Item label="商品规格">
            {getFieldDecorator('contractNumber', {
              initialValue: info.contractNumber,
              rules: [
                {
                  required: true,
                  message: '商品规格',
                },
              ],
            })(<Input placeholder="商品规格" />)}
          </Form.Item>
          <Form.Item label="商品销售属性">
            {getFieldDecorator('contractNumber', {
              initialValue: info.contractNumber,
              rules: [
                {
                  required: true,
                  message: '商品销售属性',
                },
              ],
            })(<Input placeholder="商品销售属性" />)}
          </Form.Item>
          <Form.Item label="">
            详情
          </Form.Item>
        </Form>
      </div>
      <div className="bbox bgfff">
        <p className="ctitle">物流及其他</p>
        <Form {...formItemLayout}>
          <Form.Item label="运费设置">
            {getFieldDecorator('resGoodsExtend.isFreeTrafficGoods', {
              initialValue: info.resGoodsExtend.isFreeTrafficGoods || '1',
              // onChange={e => setInfo({ ...info, yunfei: e.target.value })}
              rules: [
                {
                  required: true,
                  message: '请选择运费设置',
                },
              ],
            })(<Radio.Group onChange={e => {
              let aobj = info.resGoodsExtend
              aobj.isFreeTrafficGoods = e.target.value
              setInfo({ ...info, resGoodsExtend: aobj })
            }}>
              <Radio value="1">包邮</Radio>
              <Radio value="0">运费模板</Radio>
            </Radio.Group>)}
            { info.resGoodsExtend.isFreeTrafficGoods === '0' ? getFieldDecorator('resGoods.fareTemplateId', {
              initialValue: info.resGoods.fareTemplateId,
              rules: [
                {
                  required: true,
                  message: '请选择运费模板',
                },
              ],
            })(<Select style={{minWidth: 200}} placeholder="请选择运费模板">{templateList.map(vl => (<Option key={vl.value}>{vl.label}</Option>))}</Select>) : null }
          </Form.Item>
          <Form.Item label="是否上架">
            {getFieldDecorator('resGoods.goodsStatus', {
              initialValue: info.resGoods.goodsStatus || '2',
              rules: [
                {
                  required: true,
                  message: '请选择是否上架',
                },
              ],
            })(<Radio.Group>
              <Radio value="1">立即上架</Radio>
              <Radio value="2">放入仓库</Radio>
            </Radio.Group>)}
          </Form.Item>
          <Form.Item label="销售渠道">
            {getFieldDecorator('resGoods.salesModel', {
              initialValue: info.resGoods.salesModel || '2',
              rules: [
                {
                  required: true,
                  message: '请选择销售渠道',
                },
              ],
            })(<Radio.Group>
              <Radio value="0">线上</Radio>
              <Radio value="1">线下</Radio>
              <Radio value="2">线上和线下</Radio>
            </Radio.Group>)}
          </Form.Item>
          <Form.Item label="是否限购">
            {getFieldDecorator('resGoods.isLimit', {
              initialValue: info.resGoods.isLimit || '0',
              rules: [
                {
                  required: true,
                  message: '请选择是否限购',
                },
              ],
            })(<Radio.Group onChange={e => {
              let aobj = info.resGoods
              aobj.isLimit = e.target.value
              setInfo({ ...info, resGoods: aobj })
            }}>
              <Radio value="0">不限购</Radio>
              <Radio value="1">限购</Radio>
            </Radio.Group>)}
            { info.resGoods.isLimit === '1' ? getFieldDecorator('resGoods.limitNumber', {
              initialValue: info.resGoods.limitNumber,
              rules: [
                {
                  required: true,
                  message: '请填写限购件数',
                },
              ],
            })(<InputNumber style={{minWidth: 200}} placeholder="填写限购件数" min={1} />) : null }
          </Form.Item>
          <Form.Item label="是否开启直播">
            {getFieldDecorator('resGoods.isLiving', {
              initialValue: info.resGoods.isLiving || '0',
              rules: [
                {
                  required: true,
                  message: '请选择是否开启直播',
                },
              ],
            })(<Radio.Group>
              <Radio value="0">不开启</Radio>
              <Radio value="1">开启</Radio>
            </Radio.Group>)}
          </Form.Item>
        </Form>
      </div>
      <div style={{ textAlign: 'center', margin: '15px 0' }}>
        { hasGoodAdd ? (<Button type="primary">保存</Button>) : null }
        <Button style={{marginLeft: 15}}>返回</Button>
      </div>
      {/* 新增/修改 */}
      <Modal
        title="我的图库"
        visible={showMyImage}
        maskClosable={false}
        confirmLoading={confirmLoading}
        onOk={handleSubmit.bind(this)}
        onCancel={() => setshowMyImage(false)}
        destroyOnClose
        width={1400}
      >
        <Row>
          <Col span={8}>
            <div className="imgbox-left">
              <div className="imgbox-title btween" style={{borderRight: 0}}>
                <span>我的相册</span>
                <Button type="primary">添加相册</Button>
              </div>
              <div className="imgbox-body" style={{borderRight: 0}}>
                <Radio.Group value={curPic} onChange={val => setcurPic(val.target.value)}>
                  { picList.map(v => (<Row key={v.id}><Radio value={v.id}>{v.albumName}</Radio></Row>)) }
                </Radio.Group>
              </div>
            </div>
          </Col>
          <Col span={16}>
            <div className="imgbox-right">
              <div className="imgbox-title btween">
                <span>图片库</span>
                <Button type="primary">上传图片</Button>
              </div>
              <Row gutter={15} className="imgbox-body" style={{margin: 0}}>
                { imgs.length > 0 ? renderImgs() : (<span>暂无图片</span>) }
              </Row>
            </div>
          </Col>
        </Row>
        <Cropper
          src={curUrl}
          ref={cropper => {
            setmycropper(cropper)
          }}
          style={{height: 400, width: '100%'}}
          aspectRatio={1}
          guides={false}
        />
      </Modal>
      <Modal
        title="新增分类"
        visible={isShow}
        confirmLoading={confirmLoading}
        onOk={handleSubmit.bind(this)}
        onCancel={() => setState(false)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="分类名称">
            {getFieldDecorator('catName', {
              initialValue: info.catName,
              rules: [
                {
                  required: true,
                  message: '请填写分类名称',
                },
              ],
            })(<Input placeholder="请填写分类名称" />)}
          </Form.Item>
          <Form.Item label="上级分类">
            {getFieldDecorator('catParentId', {
              initialValue: info.catParentId || '0',
            })(<Select placeholder="请选择">
              <Option value="0">顶级分类</Option>
              {staffList.map(r => <Option key={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  global,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(addGood));
